package com.jack.helloworld.activity;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import androidx.core.app.ActivityCompat;
import androidx.appcompat.app.AppCompatActivity;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.jack.helloworld.R;

public class ContentProviderActivity extends AppCompatActivity implements View.OnClickListener {

    Button btnReadContacts;
    Button btnInsertContacts;
    TextView tvDisplayContacts;

    ContentResolver contentResolver;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_content_provider);

        initView();
        initData();
    }

    private void initView() {

        btnReadContacts = (Button) findViewById(R.id.btnReadContacts);
        btnInsertContacts = (Button) findViewById(R.id.btnInsertContacts);
        tvDisplayContacts = (TextView) findViewById(R.id.tvDisplayContacts);

        btnReadContacts.setOnClickListener(this);
        btnInsertContacts.setOnClickListener(this);

    }

    private void initData() {
        tvDisplayContacts.setMovementMethod(ScrollingMovementMethod.getInstance());
        contentResolver = getContentResolver();

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnReadContacts :
                Toast.makeText(this, R.string.read_contacts, Toast.LENGTH_SHORT).show();
                StringBuilder sb = new StringBuilder();

                if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.READ_CONTACTS}, 1);

                } else {

                    Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI,
                            new String[]{ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME}, null, null, null);

                    if (cursor != null) {
                        while (cursor.moveToNext()) {
                            int id = cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts._ID));
                            String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                            Log.e("jack", "id:" + id + " ,name:" + name);
                            sb.append("name=").append(name).append(",number=");

                            Cursor cursorPhone = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                                    new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER},
                                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + id, null, null);

                            if (cursorPhone != null) {
                                while (cursorPhone.moveToNext()) {
                                    String number = cursorPhone.getString(cursorPhone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                                    Log.e("jack", "number:" + number);
                                    sb.append(number).append(" ");
                                }
                            }

                            sb.append("\n");
                            cursorPhone.close();

                        }
                    }
                    tvDisplayContacts.setText(sb.toString());
                    cursor.close();
                }


                break;
            case R.id.btnInsertContacts :
                Toast.makeText(this, R.string.insert_contacts, Toast.LENGTH_SHORT).show();
                if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
                    Log.e("jack", "获取写联系人的权限");
                    ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.WRITE_CONTACTS}, 2);

                } else {

                    try {
                        ContentValues contentValues = new ContentValues();
                        Uri insertUri = contentResolver.insert(ContactsContract.RawContacts.CONTENT_URI, contentValues);
                        long id = ContentUris.parseId(insertUri);

                        contentValues.clear();
                        contentValues.put(ContactsContract.CommonDataKinds.StructuredName.RAW_CONTACT_ID, id);
                        contentValues.put(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, "jack");
                        contentValues.put(ContactsContract.CommonDataKinds.StructuredName.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);
                        contentResolver.insert(ContactsContract.Data.CONTENT_URI, contentValues);

                        contentValues.clear();
                        contentValues.put(ContactsContract.CommonDataKinds.Phone.RAW_CONTACT_ID, id);
                        contentValues.put(ContactsContract.CommonDataKinds.Phone.NUMBER, "123456789");
                        contentValues.put(ContactsContract.CommonDataKinds.Phone.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
                        contentResolver.insert(ContactsContract.Data.CONTENT_URI, contentValues);
                        Log.e("jack", "insert->name:jack, number:123456789");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }


                break;

        }

    }
}
